<template>
  <div>
    <PreviewDialog ref="preview"
                   :calculatorSore="calculatorSore"
                   :describeContent="describeContent"
                   :fields="fields"
                   :medicalCalculatorData="medicalCalculatorData"
                   :type="cntFormulaType"/>
    <el-container>
      <el-aside :style="{height: taskListHeight + 'px'}">
        <el-scrollbar style="height:100%;">
          <MenuItem v-for="(field, index) in tasks" :key="index" :index="index"
                    :item="field" :reorder="false" @change-selection="refreshList(index)"></MenuItem>
          <div style="text-align: right;margin-top: 15px">
            <img src="../../../../static/img/folder.png"
                 style="width: 30px; height: 20px; vertical-align: middle;display: inline-block">
            <div class="cursor" style="margin-right: 20px;display: inline-block" v-on:click="showData"><span
              style="color: red"></span>已完成的任务
              <i :class="showIcon"
                 style=" font-size: 20px;font-weight:normal "></i></div>
            <div v-if="showCompleteData">
              <MenuItem v-for="(item, index) in taskCompleteData" :key="index" :item="item" :reorder="false"
                        @change-selection="refreshFinishList(index)">
              </MenuItem>
            </div>
          </div>
        </el-scrollbar>
      </el-aside>
      <el-main style="padding: 0px 10px; ">
        <el-row class="bottom-space">
          <el-col :offset="7" :span="10">
            <el-radio-group v-model="statusParam" size="small" @change="valueChange">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button :style="{ display: statusEnable }" label="auditing">审核中</el-radio-button>
              <el-radio-button label="pass">审核通过</el-radio-button>
              <el-radio-button :style="{ display: statusEnable }" label="reject">驳回</el-radio-button>
              <el-radio-button :style="{ display: statusReleasedEnable }" label="released">已发布</el-radio-button>
            </el-radio-group>
          </el-col>
          <el-col :span="7">
            <div style="width: 100%; float: right">
              <el-input v-model="searchContent" placeholder="请输入关键词" size="small" @keyup.enter.native="updatePage">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                <i slot="suffix" v-if="showAdvance" class="el-input__icon el-icon-arrow-up" @click="switchAppend"></i>
                <i slot="suffix" v-else class="el-input__icon el-icon-arrow-down" @click="switchAppend"></i>
              </el-input>
            </div>
            <div v-if="showAdvance" class="advanced">
              <div style="padding: 5px;">
                <el-row class="bottom-space">
                  <el-col :span="24">
                    <el-select v-model="selectedLib" filterable placeholder="请选择知识库" size="small" style="width: 100%">
                      <el-option v-for="item in $store.state.knowledgeLibList"
                                 :key="item.id"
                                 :label="item.name"
                                 :value="item.id">
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row class="bottom-space">
                  <el-col :span="24">
                    <el-select v-model="selectedEditor" filterable placeholder="请选择编辑" size="small" style="width: 100%">
                      <el-option v-for="option in $store.state.userList" :key="option.id" :label="option.name"
                                 :value="option.userName">
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row class="bottom-space">
                  <el-col :span="24">
                    <el-date-picker v-model="submitDate" :picker-options="pickerOptions" align="right"
                                    end-placeholder="截止日期" range-separator="至" size="small" value-format="yyyy-MM-dd"
                                    start-placeholder="开始日期" style="width: 100%" type="daterange" unlink-panels>
                    </el-date-picker>
                  </el-col>
                </el-row>
                <el-row class="bottom-space" v-if="drugInfoLibStatus">
                  <el-col :span="24">
                    <el-input v-model="drugInfoLibCompany"
                              placeholder="请输入厂家"></el-input>
                  </el-col>
                </el-row>
                <el-row>
                  <div style="float: right">
                    <el-button size="small" @click="resetAdvanceSearch">重置</el-button>
                    <el-button size="small" type="primary" @click="doAdvanceSearch">搜索</el-button>
                  </div>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row class="bottom-space">
          <el-table highlight-current-row :data="subTasks" :height="tableHeight" border>
            <!-- v-if显示隐藏列, 会造成列排序异常, 给所有列都添加key属性解决 -->
            <el-table-column key="indexTableColumn" label="序号" type="index" width="50"></el-table-column>
            <el-table-column key="nameTableColumn" label="知识名称">
              <template slot-scope="scope">
                <div v-html="scope.row.name"></div>
              </template>
            </el-table-column>
            <el-table-column key="knowledgeLibIdTableColumn" label="所属知识库">
              <template slot-scope="scope">
                <div>{{ getLibName(scope.row.knowledgeLibId) }}</div>
              </template>
            </el-table-column>
            <el-table-column key="systemTypeTableColumn" label="所属知识体系">
              <template slot-scope="scope">
                <div>{{ getSystemName(scope.row.systemType) }}</div>
              </template>
            </el-table-column>
            <el-table-column key="drugInfoLibCompanyTableColumn" label="厂家"
                             min-width="100"
                             prop="drugInfoLibCompany" v-if="drugInfoLibStatus" show-overflow-tooltip></el-table-column>
            <el-table-column key="drugInfoLibSourceTableColumn" label="来源"
                             min-width="100"
                             prop="drugInfoLibSource" v-if="drugInfoLibStatus" show-overflow-tooltip></el-table-column>
            <el-table-column key="editorTableColumn" label="编辑">
              <template slot-scope="scope">
                <div>{{ getEditorName(scope.row.editor) }}</div>
              </template>
            </el-table-column>
            <el-table-column key="wordsCountTableColumn" label="完成字数" prop="wordsCount"></el-table-column>
            <el-table-column key="submitTimeTableColumn" label="提交日期" prop="submitTime">
              <template slot-scope="scope">
                <span v-if="UTIL.isNotEmpty(scope.row.submitTime)">{{ scope.row.submitTime.substr(0, 10) }}</span>
              </template>
            </el-table-column>
            <el-table-column key="firstAuditorTableColumn" label="初审">
              <template slot-scope="scope">
                <div>{{ getEditorName(scope.row.firstAuditor) }}</div>
              </template>
            </el-table-column>
            <el-table-column key="secondAuditorTableColumn" label="复审" v-if="crtTask.auditLevel > 1">
              <template slot-scope="scope">
                <div>{{ getEditorName(scope.row.secondAuditor) }}</div>
              </template>
            </el-table-column>
            <el-table-column key="thirdAuditorTableColumn" label="终审" v-if="crtTask.auditLevel > 2">
              <template slot-scope="scope">
                <div>{{ getEditorName(scope.row.thirdAuditor) }}</div>
              </template>
            </el-table-column>
            <el-table-column key="statusTableColumn" :show-overflow-tooltip="false" label="任务状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status === 1">初审中</span>
                <span v-else-if="scope.row.status === 2">审核通过</span>
                <span v-else-if="scope.row.status === 3" style="color: red">
                  初审驳回
                  <el-popover
                    :content="scope.row.reject"
                    trigger="hover">
                    <el-button slot="reference" style="margin-left: 10px" type="text"><a style="color: #EC0000">详情</a><i
                      class="el-icon-warning-outline el-icon--right" style="color: #EC0000"></i></el-button>
                  </el-popover>
                </span>
                <span v-else-if="scope.row.status === 4">复审中</span>
                <span v-else-if="scope.row.status === 5" style="color: red">
                  复审驳回
                  <el-popover
                    :content="scope.row.reject"
                    trigger="hover">
                    <el-button slot="reference" style="margin-left: 10px" type="text"><a style="color: #EC0000">详情</a><i
                      class="el-icon-warning-outline el-icon--right" style="color: #EC0000"></i></el-button>
                  </el-popover>
                </span>
                <span style="color: #2DB7A0" v-else-if="scope.row.status === 6">终审中</span>
                <span v-else-if="scope.row.status === 7" style="color: red">
                  终审驳回
                  <el-popover :content="scope.row.reject" trigger="hover">
                    <el-button slot="reference" style="margin-left: 10px" type="text"><a style="color: #EC0000">详情</a>
                      <i class="el-icon-warning-outline el-icon--right" style="color: #EC0000"></i>
                    </el-button>
                  </el-popover>
                </span>
                <span v-else-if="scope.row.status === 8">已发布</span>
                <span v-else-if="scope.row.status === 9" style="color: red">
                  终审通过后驳回
                  <el-popover :content="scope.row.reject" trigger="hover">
                    <el-button slot="reference" style="margin-left: 10px" type="text"><a style="color: #EC0000">详情</a>
                      <i class="el-icon-warning-outline el-icon--right" style="color: #EC0000"></i>
                    </el-button>
                  </el-popover>
                </span>
              </template>
            </el-table-column>
            <el-table-column key="operateTableColumn" label="操作">
              <template slot-scope="scope">
                <el-link v-if="scope.row.crtOperator === $store.state.user.userName" @click="audit(scope.row)">审核
                </el-link>
                <el-link @click="preview(scope.row)">详情</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 15, 20, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            background
            layout="total, sizes, prev, pager, next, jumper"
            style="float: right">
          </el-pagination>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import MenuItem from "../../common/MenuItem";
import PreviewDialog from "../../calculator/exportModel/PreviewDialog";

export default {
  name: "AllAuditTask",
  components: {PreviewDialog, MenuItem},
  props: {
    system: String,
    taskItemId: String,
    taskItemName: String,
    taskItemType: String,
    taskItemStatus: String,
  },
  data() {
    return {
      tasks: [],
      statusParam: "",
      searchContent: "",
      showAdvance: false,
      subTasks: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedLib: undefined,
      libOptions: [],
      selectedEditor: undefined,
      editorOption: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      submitDate: [],
      selectedStatus: undefined,
      currentTaskId: undefined,
      previewDialogVisible: false,
      calculatorSore: [],
      describeContent: '',
      fields: [],
      medicalCalculatorData: [],
      cntFormulaType: 1,
      tableHeight: 0,
      taskListHeight: 0,
      drugInfoLibStatus: false,
      drugInfoLibCompany: '',
      knowledgeLibId: '',
      taskCompleteData: [],
      showCompleteData: false,
      showIcon: "el-icon-caret-bottom",
      finishTaskId: '',
      statusEnable: '',
      statusReleasedEnable: 'none',
      crtTask: {},
    }
  },
  methods: {
    refreshList(index) {
      this.finishTaskId = ''
      this.statusEnable = ''
      this.statusReleasedEnable = 'none'
      this.setAllItemsUnselected()
      this.crtTask = this.tasks[index]
      this.crtTask.selected = true
      this.tasks.find(item => {
        if (item.selected == true) {
          this.taskCompleteData.forEach(field => {
            field.selected = false
          })
        }
      })
      this.currentTaskId = this.crtTask.id
      this.knowledgeLibId = this.crtTask.knowledgeLibId
      if (this.knowledgeLibId != CONST.DRUG_INFO_LIB_ID) {
        this.drugInfoLibCompany = '';
      }
      this.currentPage = 1 // 第几页
      this.pageSize = 10 // 每页显示的数据个数
      this.updateSubTaskList()
    },

    refreshFinishList(index) {
      this.setAllItemsFinishUnselected()
      this.crtTask = this.taskCompleteData[index]
      this.crtTask.selected = true
      this.taskCompleteData.find(item => {
        if (item.selected == true) {
          this.tasks.forEach(field => {
            field.selected = false
          })
        }
      })
      this.finishTaskId = this.taskCompleteData[index].id
      this.statusEnable = 'none'
      this.statusReleasedEnable = ''
      this.knowledgeLibId = this.taskCompleteData[index].knowledgeLibId
      if (this.knowledgeLibId != CONST.DRUG_INFO_LIB_ID) {
        this.drugInfoLibCompany = '';
      }
      this.currentPage = 1 // 第几页
      this.pageSize = 10 // 每页显示的数据个数
      this.finishTaskList(this.finishTaskId)
    },
    setAllItemsFinishUnselected() {
      this.taskCompleteData.forEach(field => {
        field.selected = false
      })
    },
    setAllItemsUnselected() {
      this.tasks.forEach(field => {
        field.selected = false
      })
    },
    finishTaskList(id) {
      if (this.knowledgeLibId === CONST.DRUG_INFO_LIB_ID) {
        this.drugInfoLibStatus = true;
      } else {
        this.drugInfoLibStatus = false;
      }
      this.axios.get("/pmph/action/task/selectFinishTaskItemList", {
        params: {
          page: this.currentPage,
          size: this.pageSize,
          taskId: id,
          date: JSON.stringify(this.submitDate),
          lib: this.selectedLib,
          editor: this.selectedEditor,
          name: this.searchContent,
          drugInfoLibCompany: this.drugInfoLibCompany
        }
      }).then((res) => {
        this.subTasks = res.data.subTasks
        this.total = res.data.total
      })
    },
    valueChange() {
      this.currentPage = 1 // 第几页
      this.pageSize = 10 // 每页显示的数据个数
      if (this.finishTaskId) {
        this.finishTaskList(this.finishTaskId)
      } else {
        this.updateSubTaskList()
      }
    },
    updatePage() {
      if (this.finishTaskId) {
        this.finishTaskList(this.finishTaskId)
      } else {
        this.updateSubTaskList()
      }
    },
    switchAppend() {
      this.showAdvance = !this.showAdvance
    },
    audit(row) {
      row.editOrAudit = 'audit'
      this.$store.commit('setTaskItem', row)
      if (row.systemType === CONST.SYSTEM.KNOWLEDGE_LIB) {
        this.$router.push('/knowledge/edit')
      } else if (row.systemType === CONST.SYSTEM.CALCULATOR) {
        this.$router.push({
          path: '/formula/editor',
          query: {
            id: row.knowledgeId,
            auditStatus: 'audit',
            taskItemId: row.id,
            itemStatus: row.status,
            auditLevel: row.auditLevel,
            enableCreate: row.type,
            itemName: row.name,
            nameSuggestion: JSON.stringify(row.nameSuggestion),
            status: row.status,
          }
        })
      } else if (row.systemType === CONST.SYSTEM.FLOWCHART) {
        let routeUrl = this.$router.resolve({
          path: "/knowledgeLib/MakeFlowChart",
          query: {
            id: row.knowledgeId,
            taskItemId: row.id,
            itemStatus: row.status,
            auditLevel: row.auditLevel,
            enableCreate: row.type
          },
        });
        window.open(routeUrl.href, "_blank");
      }
    },
    preview(row) {
      if (row.systemType === CONST.SYSTEM.KNOWLEDGE_LIB) {
        if (row.status === 8) {
          this.$store.commit('setKnowledgeDetailId', row.knowledgeId)
          this.$store.commit('setKnowledgeDetailStatus', 'published')
          this.$store.commit('showKnowledgeDetail')
        } else {
          this.$store.commit('setKnowledgeDetailId', row.knowledgeId)
          this.$store.commit('setKnowledgeDetailStatus', 'unpublished')
          this.$store.commit('showKnowledgeDetail')
        }
      } else if (row.systemType === CONST.SYSTEM.CALCULATOR) {
        let url = '';
        if (row.status === 8) {
          url = '/pmph/action/medicalCalculator/selectReleasedCalculatorById'
        } else {
          url = '/pmph/action/medicalCalculator/selectDataById'
        }
        this.axios.get(url, {
          params: {
            id: row.knowledgeId,
          }
        }).then((response) => {
          let that = this
          that.medicalCalculatorData = response.data.medicalCalculatorData
          that.calculatorSore = response.data.calculatorSore
          that.describeContent = response.data.describeContent
          if (!this.describeContent) {
            this.describeContent = '无'
          }
          that.fields = response.data.fields
          for (let i = 0; i < that.fields.length; i++) {
            if (that.fields[i].kind === 1) {
              that.fields[i].property = JSON.parse(that.fields[i].property)
            }
          }
          that.cntFormulaType = response.data.type
          this.previewDialogVisible = true
        }).catch((error) => {
          console.error(error)
          this.$message.error("获取计算器数据失败")
        })
      } else if (row.systemType === CONST.SYSTEM.FLOWCHART) {
        let routeUrl = this.$router.resolve({
          path: "/flowchart/mobileViewFlowChart",
          query: {id: row.knowledgeId},
        });
        window.open(routeUrl.href, "_blank");
      }
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.updatePage()
    },
    handleCurrentChange(value) {
      this.currentPage = value
      if (this.finishTaskId) {
        this.finishTaskList(this.finishTaskId)
      } else {
        this.updateSubTaskList()
      }
    },
    updateTaskList() {
      this.axios.get("/pmph/action/task/selectAuditTaskList", {
        params: {
          systemType: this.system === 'all' ? '' : this.system
        }
      }).then((res) => {
        this.tasks = res.data.result
        this.taskCompleteData = res.data.completeResult;
        if (this.taskItemId) {
          this.crtTask = this.tasks.find(task => task.id === this.taskItemId)
          if (UTIL.nonNullObj(this.crtTask)) {
            this.crtTask.selected = true
            this.currentTaskId = this.crtTask.id
            this.knowledgeLibId = this.crtTask.knowledgeLibId
          }
          if (UTIL.isNotEmpty(this.taskItemName)) {
            this.searchContent = this.taskItemName
          }
          this.currentTaskId = this.taskItemId
          this.knowledgeLibId = this.knowledgeLibId
        } else if (this.tasks.length > 0) {
          this.crtTask = this.tasks[0]
          this.crtTask.selected = true
          this.currentTaskId = this.crtTask.id
          this.knowledgeLibId = this.crtTask.knowledgeLibId
        }
        if (UTIL.nonNullObj(this.crtTask)) {
          this.updateSubTaskList();
        }
      })
    },
    updateSubTaskList() {
      if (!this.currentTaskId) {
        return
      }
      if (this.knowledgeLibId === CONST.DRUG_INFO_LIB_ID) {
        this.drugInfoLibStatus = true;
      } else {
        this.drugInfoLibStatus = false;
      }
      this.axios.get("/pmph/action/task/selectSubTaskList", {
        params: {
          system: this.system,
          page: this.currentPage - 1,
          size: this.pageSize,
          status: this.statusParam,
          lib: this.selectedLib,
          editor: this.selectedEditor,
          date: JSON.stringify(this.submitDate),
          taskId: this.currentTaskId,
          name: this.searchContent,
          drugInfoLibCompany: this.drugInfoLibCompany
        }
      }).then((res) => {
        this.subTasks = res.data.subTasks
        this.total = res.data.total
      })
    },
    getLibName(libId) {
      if ("calculator_lib_id" === libId) {
        return "医学计算器"
      } else if ("flow_chart_lib_id" === libId) {
        return "流程图"
      } else {
        return UTIL.getNameById(this.$store.state.knowledgeLibList, libId)
      }
      return ''
    },
    getSystemName(systemId) {
      return CONST.SYSTEM_TYPE.find(item => item.value === systemId).label
    },
    getEditorName(userId) {
      if (userId) {
        return this.$store.state.userList.find(item => item.userName === userId).name
      }
      return ''
    },
    resetAdvanceSearch() {
      this.selectedLib = undefined
      this.selectedEditor = undefined
      this.submitDate = []
      this.drugInfoLibCompany = ''
    },
    doAdvanceSearch() {
      this.currentPage = 1 // 第几页
      this.pageSize = 10 // 每页显示的数据个数
      if (this.finishTaskId) {
        this.finishTaskList(this.finishTaskId)
      } else {
        this.updateSubTaskList()
      }
    },
    visibilitychange() {

      if (document.visibilityState !== "hidden") {
        this.updateSubTaskList();
        if (this.currentTaskId) {
          this.taskItemId = this.currentTaskId
          this.updateTaskList()
        }
      }
    },
    addVisibilityChange() {

      if (this.system === 'flowchart' || this.system === 'all') {
        window.addEventListener("visibilitychange", this.visibilitychange)
      }
    },
    removeVisibilityChange() {
      window.removeEventListener("visibilitychange", this.visibilitychange)
    },
    showData() {
      if (this.showCompleteData) {
        this.showCompleteData = false;
        this.showIcon = "el-icon-caret-left";
      } else {
        this.showCompleteData = true;
        this.showIcon = "el-icon-caret-bottom";
      }
    }
  },
  activated() {
    this.addVisibilityChange()
    if (this.$route.meta.isUseCache) {
      this.updateSubTaskList();
      if (this.currentTaskId) {
        this.taskItemId = this.currentTaskId
        this.updateTaskList()
      }
    } else {
      this.updateSubTaskList()
      this.updateTaskList()
    }

  },
  created() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 150
    this.taskListHeight = CONST.WORKSPACE_HEIGHT - 70
    this.updateTaskList()
  }
}
</script>

<style scoped>
.advanced {
  width: 378px;
  position: absolute;
  top: 35px;
  right: 1px;
  z-index: 100;
  background-color: white;
  border-radius: 3px;
  border: 1px solid #EBEEF5;
  box-shadow: 0 2px 12px 0 rgba(0 0 0 0.1);
  padding: 10px;
}

.bottom-space {
  margin-bottom: 10px;
}

/deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
}

.cursor {
  cursor: pointer;
}
</style>
